package mybatisplus.spring.boot.admin.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    /**
     * @param milliSecond 毫秒数
     * @return 格式化的时间
     */
    public static String datePoor(Long milliSecond) {
        long nd = 1000 * 24 * 60 * 60;//每天毫秒数
        long nh = 1000 * 60 * 60;//每小时毫秒数
        long nm = 1000 * 60;//每分钟毫秒数
        long ns = 1000;//每分钟毫秒数

        long day = milliSecond / nd;   // 计算差多少天
        long hour = milliSecond % nd / nh; // 计算差多少小时
        long min = milliSecond % nd % nh / nm;  // 计算差多少分钟
        long seconds = milliSecond % nd % nh % nm / ns;  // 计算差多少秒

        StringBuilder sBuilder = new StringBuilder();
        if (day > 0) sBuilder.append(day + "天");
        if (hour > 0) sBuilder.append(hour + "小时");
        if (min > 0) sBuilder.append(min + "分钟");
        if (seconds > 0) sBuilder.append(seconds + "秒");

        return sBuilder.toString();
    }

    /**
     * @param milliSecond 毫秒数
     * @return 格式化的时间
     */
    public static String datePoorMinute(Long milliSecond) {
        long nd = 1000 * 24 * 60 * 60;//每天毫秒数
        long nh = 1000 * 60 * 60;//每小时毫秒数
        long nm = 1000 * 60;//每分钟毫秒数

        long day = milliSecond / nd;   // 计算差多少天
        long hour = milliSecond % nd / nh; // 计算差多少小时
        long min = milliSecond % nd % nh / nm;  // 计算差多少分钟

        StringBuilder sBuilder = new StringBuilder();
        if (day > 0) sBuilder.append(day + "天");
        if (hour > 0) sBuilder.append(hour + "小时");
        if (min > 0) sBuilder.append(min + "分钟");

        return sBuilder.toString();
    }

    public static String yyyyMMdd="yyyy-MM-dd";

    public static String yMd="yyyy-MM-dd";

    public static String 年月日="yyyy年MM月dd日";

    public static String yyyyMM="yyyy-MM";

    public static String year="yyyy";

    public static String month="MM";

    public static String day="dd";

    public static String yyyyMMddHHmmss="yyyy-MM-dd HH:mm:ss";

    public static String yMdHms="yyyy-MM-dd HH:mm:ss";

    public static String HHmmss="HH:mm:ss";

    public static String getYear() {
        return format(new Date(), year);
    }

    public static String getMonth() {
        return format(new Date(), month);
    }

    public static String getday() {
        return format(new Date(), day);
    }

    public static String getNow_yyyyMMdd() {
        return format(new Date(), yyyyMMdd);
    }
    public static String getNow_yMd() {
        return format(new Date(), yMd);
    }

    public static long str2Long(String str, String pattern) {
        return str2Date(str, pattern).getTime();
    }

    public static Date str2Date(String str, String pattern) {
        if(str==null || str.trim().length()==0) return null;
        Date date=null;
        try {
            SimpleDateFormat format=new SimpleDateFormat(pattern);
            date=format.parse(str);
        } catch(ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static long getCurrentTime2Long() {
        return System.currentTimeMillis();
    }

    public static Date getCurrentTime2Date() {
        return new Date();
    }

    public static String format(Date date, String pattern) {
        SimpleDateFormat sdf=new SimpleDateFormat(pattern);
        try {
            return sdf.format(date);
        } catch(Exception e) {
            return null;
        }

    }
    public static Date parse(String date, String pattern) {
        SimpleDateFormat sdf=new SimpleDateFormat(pattern);
        try {
            return sdf.parse(date);
        } catch(Exception e) {
            return null;
        }

    }
    public static String formatYmd(Date date) {
        SimpleDateFormat sdf=new SimpleDateFormat(yMd);
        try {
            return sdf.format(date);
        } catch(Exception e) {
            return null;
        }

    }

    public static String formatNowYmd() {
        SimpleDateFormat sdf=new SimpleDateFormat(yMd);
        try {
            return sdf.format(new Date());
        } catch(Exception e) {
            return null;
        }

    }

    public static String format(String date, String pattern) {
        Date d=str2Date(date, pattern);
        SimpleDateFormat sdf=new SimpleDateFormat(pattern);
        try {
            return sdf.format(d);
        } catch(Exception e) {
            return null;
        }

    }

    public static int getYear(Date date) {
        SimpleDateFormat sdf=new SimpleDateFormat("YYYY");
        try {
            return Integer.parseInt(sdf.format(date));
        } catch(Exception e) {
            return 0;
        }

    }

    public static String defaultFormat(Date date) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    public static String addDay(String date, String pattern, int addDay, Integer setHour, Integer setMinute, Integer setSecond) {
        Calendar cale=Calendar.getInstance();
        if(!StringUtil.isNull(date)) {
            cale.setTime(str2Date(date, pattern));
        }
        if(setHour != null) {
            cale.set(Calendar.HOUR_OF_DAY, setHour);
        }
        if(setMinute != null) {
            cale.set(Calendar.MINUTE, setMinute);
        }
        if(setSecond != null) {
            cale.set(Calendar.SECOND, setSecond);
        }
        cale.set(Calendar.DATE, cale.get(Calendar.DATE) + addDay);

        return format(cale.getTime(), pattern);
    }


    public static Date addDay(Date date, String pattern, int addDay, Integer setHour, Integer setMinute, Integer setSecond) {
        Calendar cale=Calendar.getInstance();
        if(date != null) {
            cale.setTime(date);
        }
        if(setHour != null) {
            cale.set(Calendar.HOUR_OF_DAY, setHour);
        }
        if(setMinute != null) {
            cale.set(Calendar.MINUTE, setMinute);
        }
        if(setSecond != null) {
            cale.set(Calendar.SECOND, setSecond);
        }
        cale.set(Calendar.DATE, cale.get(Calendar.DATE) + addDay);

        return cale.getTime();
    }

    public static String addYear(String date, String pattern, int addYear, Integer setMonth, Integer setDay) {
        Calendar cale=Calendar.getInstance();
        if(!StringUtil.isNull(date)) {
            cale.setTime(str2Date(date, pattern));
        }
        cale.set(Calendar.YEAR, cale.get(Calendar.YEAR) + addYear);
        if(setMonth != null) {
            cale.set(Calendar.MONTH, setMonth - 1);
        }
        if(setDay != null) {
            cale.set(Calendar.DAY_OF_MONTH, setDay);
        }
        return format(cale.getTime(), pattern);
    }

    public static String addYear_(String date, String pattern, int addYear, Integer addMonth, Integer addDay) {
        Calendar cale=Calendar.getInstance();
        if(!StringUtil.isNull(date)) {
            cale.setTime(str2Date(date, pattern));
        }
        cale.set(Calendar.YEAR, cale.get(Calendar.YEAR) + addYear);
        cale.set(Calendar.MONTH, cale.get(Calendar.MONTH) + addMonth);
        cale.set(Calendar.DAY_OF_MONTH, cale.get(Calendar.DAY_OF_MONTH) + addDay);

        return format(cale.getTime(), pattern);
    }

    public static String addYear_(Date date, String pattern, int addYear, int addMonth, int addDay) {
        Calendar cale=Calendar.getInstance();
        cale.setTime(date);
        cale.set(Calendar.YEAR, cale.get(Calendar.YEAR) + addYear);
        cale.set(Calendar.MONTH, cale.get(Calendar.MONTH) + addMonth);
        cale.set(Calendar.DAY_OF_MONTH, cale.get(Calendar.DAY_OF_MONTH) + addDay);

        return format(cale.getTime(), pattern);
    }

    /**
     * 判断哪一天更早,如果date1早return 2; date2早rerutn -1; 相等return 0; compareTime("2015-3-21", "2015-3-22", "yyyy-MM-dd") return 2
     * @param date1
     * @param date2
     * @param pattern
     * @return
     */
    public static Integer compareTime(String date1, String date2, String pattern) {

        try {
            Long long1=str2Long(date1, pattern);
            Long long2=str2Long(date2, pattern);
            if(long1 - long2 > 0) {
                return -1;
            } else if(long1 - long2 < 0) {
                return 2;
            } else {
                return 0;
            }

        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 判断哪一天更早,如果date1早return 2; date2早rerutn -1; 相等return 0; compareTime("2015-3-21", "2015-3-22", "yyyy-MM-dd") return 2
     * @param date1
     * @param date2
     * @param pattern
     * @return
     */
    public static Integer compareTime(Date date1, Date date2, String pattern) {

        try {
            Long long1=str2Date(format(date1, pattern), pattern).getTime();
            Long long2=str2Date(format(date2, pattern), pattern).getTime();
            if(long1 - long2 > 0) {
                return -1;
            } else if(long1 - long2 < 0) {
                return 2;
            } else {
                return 0;
            }

        } catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取一个月份区间
     * @param time yyyy-MM格式的月份
     * @return
     */
    public static String getaMonth(String time) {
        String begin=null;
        if(time.length() == 7)
            begin=time + "-01";
        else
            begin=time.split("-")[0] + "-0" + time.split("-")[1] + "-01";
        Date end=str2Date(addYear(begin, "yyyy-MM-dd", 0, Integer.parseInt(time.split("-")[1]) + 1, 0), "yyyy-MM-dd");
        return begin + "," + format(end, "yyyy-MM-dd")+" 23:59:59";
    }

    /**
     * 获取两个时间相差几天
     */
    public static Integer daysBetween(Date smdate, Date bdate) throws ParseException {
        if(smdate==null || bdate==null) return null;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal=Calendar.getInstance();
        cal.setTime(smdate);
        long time1=cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2=cal.getTimeInMillis();
        long between_days=(time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 获取两个时间相差几天：返回负数，0，正数
     */
    public static int daysBetween(String smdate, String bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal=Calendar.getInstance();
        cal.setTime(sdf.parse(smdate));
        long time1=cal.getTimeInMillis();
        cal.setTime(sdf.parse(bdate));
        long time2=cal.getTimeInMillis();
        long between_days=(time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * @param birthDay: 20110113 (yyyyMMdd)
     * @return
     */
    public static Integer getAge(String birthDay){
        String[] now=getNow_yyyyMMdd().split("-");
        Integer year= Integer.parseInt(now[0]);
        Integer md= Integer.parseInt(now[1]+now[2]);

        Integer ageYear= Integer.parseInt(birthDay.substring(0, 4));
        Integer agemd= Integer.parseInt(birthDay.substring(4, 8));

        Integer age=year-ageYear;
        if(md>agemd) return age;
        else return age-1;
    }


    /**
     * 获取当前日期或给定日期的工作日的起点时刻：用于代扣收入T+1提现（经过一个工作日可提现不是经过24小时）
     * 即：如果是工作日即获取本日开始时刻，如果是周末就获取本周五的开始时刻
     * @return
     */
    public static Date getLastWorkDay(Date date){
        Calendar workDayStart = Calendar.getInstance();
        if(date!=null) workDayStart.setTime(date);
        int today = workDayStart.get(Calendar.DAY_OF_WEEK)-1;//取得今天的星期值
        if(today == 0){//星期天
            workDayStart.roll(Calendar.DAY_OF_YEAR, -2);
        }else if(today == 6){//星期六
            workDayStart.roll(Calendar.DAY_OF_YEAR, -1);
        }
        workDayStart.set(Calendar.HOUR_OF_DAY, 0);
        workDayStart.set(Calendar.MINUTE, 0);
        workDayStart.set(Calendar.SECOND, 1);
        return workDayStart.getTime();
    }

    public static Long dateDiff(Date startTime, Date endTime) throws ParseException {
        long ns=1000;// 一秒钟的毫秒数long
        long diff=endTime.getTime() - startTime.getTime();
        long sec=diff / ns;// 计算差多少秒
        return sec;
    }

    public static Long dateDiff(String startTime, String endTime, String format) throws ParseException {
        // 按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd=new SimpleDateFormat(format);
        long nd=1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh=1000 * 60 * 60;// 一小时的毫秒数
        long nm=1000 * 60;// 一分钟的毫秒数
        long ns=1000;// 一秒钟的毫秒数long diff;try {
        // 获得两个时间的毫秒时间差异
        long diff=sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
//        long day=diff / nd;// 计算差多少天
//        long hour=diff % nd / nh;// 计算差多少小时
//        long min=diff % nd % nh / nm;// 计算差多少分钟
        long sec=diff % nd % nh % nm / ns;// 计算差多少秒//输出结果
//        System.out.println("时间相差：" + day + "天" + hour + "小时" + min + "分钟" + sec + "秒。");
        return sec;
    }

    public static Date addYears(Date date, Integer n){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, n);
        return calendar.getTime();
    }

    public static void main(String[] args) throws ParseException {
        try {
            System.out.println(DateUtil.daysBetween("2015-01-01", "2015-01-01"));
            System.out.println(DateUtil.daysBetween("2015-01-02", "2015-01-01"));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}
